package com.zhongyu.scheduler.consumer.service.impl;

import com.zhongyu.comm.pojo.Item;
import com.zhongyu.comm.pojo.SchedulerSeat;
import com.zhongyu.comm.pojo.SchedulerSeatPrice;
import com.zhongyu.comm.pojo.Task;
import com.zhongyu.comm.util.OrderException;
import com.zhongyu.comm.vo.CreateOrderVo;
import com.zhongyu.scheduler.consumer.client.ItemClient;
import com.zhongyu.scheduler.consumer.client.SchedulerClient;
import com.zhongyu.scheduler.consumer.client.SchedulerSeatClient;
import com.zhongyu.scheduler.consumer.client.SchedulerSeatPriceClient;
import com.zhongyu.scheduler.consumer.service.SchedulerSeatService;
import com.zhongyu.scheduler.consumer.service.SchedulerService;
import com.zhongyu.scheduler.consumer.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service("schedulerSeatService")
public class SchedulerSeatServiceImpl implements SchedulerSeatService {

    @Resource
    private SchedulerSeatClient schedulerSeatClient;

    @Resource
    private SchedulerSeatPriceClient schedulerSeatPriceClient;
    @Resource
    private SchedulerClient schedulerClient;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ItemClient itemClient;

    private RedisTemplate redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        this.redisTemplate = redisTemplate;
    }

    @Override
    public SeatArrayVo queryOriginalCinemaSeatArray(Integer scheduleId) {
        List<SchedulerSeat> seats = schedulerSeatClient.findByScheduleId(scheduleId);
        Integer max = 0;
        if (seats.size() > 0) {
            max = seats.stream().max(new Comparator<SchedulerSeat>() {
                @Override
                public int compare(SchedulerSeat o1, SchedulerSeat o2) {
                    return o1.getX() - o2.getX();
                }
            }).get().getX();
        }
        List<String> list = new ArrayList<>();

        for (int i = 1; i <= max; i++) {
            StringBuffer sbf = new StringBuffer();
            for (SchedulerSeat seat : seats) {
                if (seat.getX() == i) {
                    switch (seat.getAreaLevel()) {
                        case 0:
                            sbf.append("_");
                            break;
                        case 1:
                            sbf.append("a");
                            break;
                        case 2:
                            sbf.append("b");
                            break;
                        case 3:
                            sbf.append("c");
                            break;
                        default:
                            sbf.append("_");

                    }
                }
            }
            list.add(sbf.toString());
        }
        SeatArrayVo vo=new SeatArrayVo();
        vo.setSeatArray(list);
         return vo;
    }

    @Override
    public CinemaSeatVo queryCinemaSeatArrayByScheduleId(Integer scheduleId, Integer cinemaId) {
       CinemaSeatVo vo=new CinemaSeatVo();
       vo.setCinemaId(cinemaId);
       vo.setScheduleId(scheduleId);
     List<SchedulerSeatPrice> list01=  schedulerSeatPriceClient.findBySchedulerId(scheduleId);
    List<SeatPriceVo> seatPriceList=  list01.stream().map(schedulerSeatPrice -> {
          SeatPriceVo seatPriceVo=new SeatPriceVo();
        /*  Character ch= (char) (64+schedulerSeatPrice.getAreaLevel());
          seatPriceVo.setAreaLevelName(ch.toString());*/
        char ch= (char) (64+schedulerSeatPrice.getAreaLevel());
        seatPriceVo.setAreaLevelName(""+ch);
        seatPriceVo.setPrice(schedulerSeatPrice.getPrice());
          /*switch (schedulerSeatPrice.getAreaLevel()){
              case 1:
                  seatPriceVo.setAreaLevelName("A");
                  break;
              case 2:
                  seatPriceVo.setAreaLevelName("B");
                  break;
              case 3:
                  seatPriceVo.setAreaLevelName("C");
          }*/
        return seatPriceVo;
      }).collect(Collectors.toList());
    vo.setSeatPriceList(seatPriceList);

    List<SchedulerSeat> list02=schedulerSeatClient.findByScheduleId(scheduleId);
    List<SeatInfoVo> seatInfoList=list02.stream().map(schedulerSeat -> {
        SeatInfoVo seatInfoVo=new SeatInfoVo();
        BeanUtils.copyProperties(schedulerSeat,seatInfoVo);
        seatInfoVo.setCinemaId(cinemaId);
        SchedulerSeatPrice schedulerSeatPrice=schedulerSeatPriceClient.findPrice(scheduleId,seatInfoVo.getAreaLevel());
        if(schedulerSeatPrice!=null) {
            seatInfoVo.setPrice(schedulerSeatPrice.getPrice());
        }
        return seatInfoVo;
    }).collect(Collectors.toList());
    vo.setSeatInfoList(seatInfoList);

        return vo;
    }

    /**
     *
     * @param createOrderVo
     * @return
     */
    @Override
    public String lockSeatAndUpdate(CreateOrderVo createOrderVo) throws OrderException{
//      Integer itemId=  createOrderVo.getItemId();
//     Item item= itemClient.findById(itemId);
//     if (item==null){
//         throw new OrderException("传入的剧目编号无效");
//     }
      Integer schedulerId=createOrderVo.getSchedulerId();
        String orderNo=null;
        String seatPositions=createOrderVo.getSeatPositions();
        String[] seats=seatPositions.split(",");
        SetOperations setOperations= redisTemplate.opsForSet();
        for (String seat:seats){
          boolean flag=  setOperations.isMember("scheduler:key:"+schedulerId,seat);
         if (flag==true){
             throw new OrderException("所定座位已被占用！");
         }
        }
   RLock rLock= redissonClient.getLock("scheduler:lock:"+schedulerId);
   rLock.lock();
   try {
       log.debug("HHHHHHHHH:"+createOrderVo);
        orderNo = schedulerSeatClient.updateSeatAndAddTask(createOrderVo);
      setOperations.add("scheduler:key:"+schedulerId,seats);
   }finally {
       rLock.unlock();
   }
        return orderNo;
    }


}
